<!--
 @description
 @fileName CavansWater.vue
 @author zengqiongying
 @created 2022/11/19 15:36:53
-->
<template>
  <div>
    <canvas id="canvas" ref="canvas" />
  </div>
</template>

<script>
export default {
  name: 'Cavans',
  data() {
    return {
      canvas: null,
      canvasWidth: 375,
      canvasHeight: 46,
      xOffset: 0, // 初始便宜
      speed: 0.06 // 偏移速度
    }
  },

  computed: {},

  created() {
    // for (let x = 0; x < 3; x += 0.053) {
    //   const y = 23 * Math.sin((0 + x) * 375 + 0)
    //   console.log(x, (46 / 2) + y)
    // }
  },
  activated() {},

  mounted() {
    this.$nextTick(() => {
      this.initCavans()
    })
  },

  methods: {
    initCavans() {
      const canvas = this.$refs.canvas
      // const canvas = document.getElementById('canvas')
      canvas.width = 375 // window.innerWidth // 375
      canvas.height = 48
      this.canvas = canvas
      this.canvasWidth = canvas.width
      this.canvasHeight = canvas.height

      this.draw()
      // requestAnimationFrame(this.draw.bind(this, canvas))
    },
    draw() {
      const canvas = this.canvas
      const ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      // 曲线绘制
      this.drawSin(ctx, 'rgba(22, 188, 131, 1)', -50, this.xOffset, 2)
      this.drawSin(ctx, 'rgba(98, 142, 255, 0.3)', -20, this.xOffset)
      this.drawSin(ctx, 'rgba(98, 142, 255, 0.12)', -5, this.xOffset)

      this.xOffset += this.speed
      requestAnimationFrame(this.draw.bind(this))
    },
    // 根据定义波浪的参数配置，通过公式：y = 波浪高度 * sin(x * 波浪宽度 + 水平位移)，来绘制正弦曲线
    drawSin(ctx, color, startX = 0, xOffset = 0, lineW = 1) {
      const points = []
      const canvasWidth = this.canvasWidth
      const canvasHeight = this.canvasHeight
      const waveWidth = 2 * Math.PI / canvasWidth // 0.018 // 波浪宽度,数越小越宽
      const waveHeight = 23 // 波浪高度,数越大越高
      const h = canvasHeight / 2
      // const xOffset = 0 // 水平位移

      ctx.beginPath()
      ctx.moveTo(0, waveHeight + startX)// 波浪线起点坐标
      for (let x = startX; x < canvasWidth; x += 20 / canvasWidth) {
        const y = waveHeight * Math.sin((startX + x) * waveWidth + xOffset)
        points.push([x, h + y])
        ctx.lineTo(x, h + y)
      }
      // ctx.lineTo(canvasWidth, -canvasHeight)
      // ctx.lineTo(0, -canvasHeight)
      // ctx.lineTo(points[0][0], points[0][1])

      // ctx.closePath()
      ctx.lineWidth = lineW
      ctx.strokeStyle = color
      ctx.stroke()
    }
  }
}

</script>
<style lang='less' scoped>
</style>
